//
// Created by zhengjuping on 24-9-9.
//

#include <cstdlib>
#include <cstring>
#include "include/GattAttributeTable.h"

GattAttribute::GattAttribute(bool autoRsp,
                             const BleUuid& uuid,
                             uint16_t perm,
                             uint16_t max_length,
                             uint16_t length,
                             uint8_t *value):
                            _autoRsp(autoRsp),
                            _bleUuid(uuid),
                            _perm(perm),
                            _max_length(max_length),
                            _length(length){

    _attr_db.attr_control.auto_rsp = _autoRsp;
    switch (_bleUuid.getWidth()) {
        case BleUuid::Width::UUID_16:{
            _uuid16 = _bleUuid.getUuid16();
            _attr_db.att_desc.uuid_p = (uint8_t *)&_uuid16;
            _attr_db.att_desc.uuid_length = 2;
            break;
        }
        case BleUuid::Width::UUID_32:
            _uuid32 = _bleUuid.getUuid32();
            _attr_db.att_desc.uuid_p = (uint8_t *)&_uuid32;
            _attr_db.att_desc.uuid_length = 4;
            break;
        default:
            abort();
    }
    _attr_db.att_desc.perm = _perm;
    _attr_db.att_desc.max_length = _max_length;
    _attr_db.att_desc.length = _length;
    _value = (uint8_t *)malloc(_length);
    memcpy(_value, value, _length);
    _attr_db.att_desc.value = _value;
}

int32_t GattAttribute::getGattsAttrDb(esp_gatts_attr_db_t &attr_db) {
    attr_db = _attr_db;
    return 0;
}

GattAttribute::~GattAttribute() {
    free(_value);
    _value = nullptr;
}
